package red.mlz.gameservice.controller.category;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import red.mlz.common.entity.category.Category;
import red.mlz.gameservice.domain.category.CategoriesTreeVo;
import red.mlz.gameservice.domain.category.CategoryItemVo;
import red.mlz.gameservice.domain.category.CategoryListVo;
import red.mlz.gameservice.domain.category.CategoryTreeVo;
import red.mlz.gameservice.service.category.CategoryService;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @RequestMapping ("/game-service/category/total")
    public long getTotalCount() {
        return categoryService.getTotalCount();
    }

    @RequestMapping("/game-service/category/page")
    public List<Category> getByPage(@RequestParam(name = "page") int page,
                                    @RequestParam(name = "size") int size) {
        return categoryService.getByPage(page, size);
    }

    @RequestMapping("/game-service/category/getById")
    public Category getById(@RequestParam(name = "id")Long id){
        return categoryService.getById(id);
    }
    @RequestMapping("/game-service/category/getCategoryNameByParentId")
    public List<String> getCategoryNameByParentId(@RequestParam(name = "parentId")Long parentId) {
        return categoryService.getCategoryNameByParentId(parentId);
    }

    //批量查询分类信息
    @RequestMapping("/game-service/category/listByIds")
    public List<Category> getListByIds(@RequestParam(name = "categoryIds") List<Long> categoryIds){
        return categoryService.listByIds(categoryIds);
    }

    @RequestMapping("/game-service/category/list")
    public CategoryListVo getCategoryList() {

        List <Category> categories = categoryService.findAll();

        List<CategoryTreeVo> tree = categories.stream()
                .filter(c -> c.getParentId() == null) // 筛选父分类
                .map(parent -> {
                    // 创建父节点 VO
                    CategoryTreeVo parentVO = new CategoryTreeVo();
                    parentVO.setId(parent.getId());
                    parentVO.setImage(parent.getImage());
                    parentVO.setName(parent.getName());


                    // 收集子分类并映射为 ItemVO
                    List<CategoryItemVo> children = categories.stream()
                            .filter(child -> parent.getId().equals(child.getParentId()))
                            .map(child -> new CategoryItemVo(
                                    child.getId(),
                                    child.getImage(),
                                    child.getName()
                            ))
                            .collect(Collectors.toList());

                    parentVO.setChildren(children);
                    return parentVO;
                })
                .collect(Collectors.toList());

        CategoryListVo categoryListVo = new CategoryListVo();
        categoryListVo.setList(tree);

        return categoryListVo;
    }

    @RequestMapping("/game-service/category/third_level_category")
    public Map<String, Object> getThirdLevelCategory(@RequestParam Long parentId,
                                          @RequestParam(required = false) Long selectedId) {
        List<Category> categories = categoryService.findAll();

        //筛选三级类目
        List<Map<String,Object>> thirdLevelCategories = categories.stream()
                .filter(c ->parentId.equals(c.getParentId()))
                .map(c -> {
                    Map<String,Object> categoryMap = new HashMap<>();
                    categoryMap.put("id",c.getId());
                    categoryMap.put("name", c.getName());
                    categoryMap.put("image", c.getImage());
                    return categoryMap;
                })
                .collect(Collectors.toList());

        // 获取选中类目的详细信息
        Map<String, Object> selectedCategory = new HashMap<>();
        if (selectedId != null) {
            Optional<Category> optionalCategory = categories.stream()
                    .filter(c -> c.getId().equals(selectedId))
                    .findFirst();
            if (optionalCategory.isPresent()) {
                Category category = optionalCategory.get();
                selectedCategory.put("id", category.getId());
                selectedCategory.put("name", category.getName());
                selectedCategory.put("image", category.getImage());
            }
        } else if (!thirdLevelCategories.isEmpty()) {
            // 如果没有指定 selectedId，默认选中第一个类目
            Map<String, Object> firstCategory = thirdLevelCategories.get(0);
            selectedCategory.put("id", firstCategory.get("id"));
            selectedCategory.put("name", firstCategory.get("name"));
            selectedCategory.put("image", firstCategory.get("image"));
        }

        // 构建响应
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("thirdLevelCategories", thirdLevelCategories);
        result.put("categoryContent", selectedCategory);

        return result;
    }

    @RequestMapping("/game-service/category/tree")
    public Map<String, Object> getCategoryTree() {

        List<Category> categories = categoryService.findAll();

        // 构建类目树
        List<CategoriesTreeVo> categoryTree = buildCategoryTree(categories);

        // 构建响应
        Map<String, Object> result = new HashMap<>();
        result.put("categoryTree", categoryTree);

        return result;
    }

    @RequestMapping("/game-service/category/edit")
    public Long edit(@RequestParam(name = "categoryId") Long categoryId,
                @RequestParam(name = "name")String name,
                @RequestParam(name = "image")String image,
                @RequestParam(name = "parentId",required = false)Long parentId){
        return categoryService.edit( categoryId, name, image, parentId);
    }

    @RequestMapping("/game-service/category/add")
    public String addCategory(@RequestParam(name = "categoryId",required = false) Long categoryId,
                                @RequestParam(name = "name") String name,
                                @RequestParam(name = "image") String image,
                                @RequestParam(name = "parentId") Long parentId) {

        Long resultCategoryId = categoryService.edit(categoryId, name, image,parentId);
        return resultCategoryId.toString();
    }

    @RequestMapping("/game-service/category/update")
    public String updateCategory(@RequestParam(name = "categoryId") Long categoryId,
                                   @RequestParam(name = "name") String name,
                                   @RequestParam(name = "image") String image,
                                   @RequestParam(name = "parentId") Long parentId){
        try {
            Long resultCategoryId = categoryService.edit(categoryId, name, image,parentId);
            return resultCategoryId.toString();
        }catch (Exception e) {
            return e.getMessage();
        }
    }

    @RequestMapping("/game-service/category/delete")
    public Integer deleteCategory(@RequestParam(name = "categoryId") Long categoryId){
        return categoryService.delete(categoryId);
    }

    // 递归构建类目树
    private List<CategoriesTreeVo> buildCategoryTree(List<Category> categories) {
        return categories.stream()
                .filter(c -> c.getParentId() == null) // 筛选顶级类目
                .map(parent -> {
                    CategoriesTreeVo parentVO = new CategoriesTreeVo();
                    parentVO.setId(parent.getId());
                    parentVO.setName(parent.getName());
                    parentVO.setImage(parent.getImage());

                    // 递归构建子类目
                    List<CategoriesTreeVo> children = buildSubCategories(categories, parent.getId());
                    parentVO.setChildren(children);

                    return parentVO;
                })
                .collect(Collectors.toList());
    }

    // 递归构建子类目
    private List<CategoriesTreeVo> buildSubCategories(List<Category> categories, Long parentId) {
        return categories.stream()
                .filter(c -> parentId != 0 && parentId.equals(c.getParentId()))
                .map(child -> {
                    CategoriesTreeVo childVO = new CategoriesTreeVo();
                    childVO.setId(child.getId());
                    childVO.setName(child.getName());
                    childVO.setImage(child.getImage());

                    // 递归构建孙类目
                    List<CategoriesTreeVo> grandchildren = buildSubCategories(categories, child.getId());
                    childVO.setChildren(grandchildren);

                    return childVO;
                })
                .collect(Collectors.toList());
    }

}
